package test;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
    /**
     * 上传数据及保存文件
     */
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        File savepath = new File("D:\\test1");
        if (!savepath.exists()) {
            savepath.mkdir();
        }
        factory.setRepository(savepath);
        

        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        //中文处理
        upload.setHeaderEncoding("UTF-8"); 

        String uploadPath = "D:\\test";

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        System.out.println(fileName);
                        if(hasfile(fileName)==-1) {
                        	continue;
                        }
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message","文件上传成功!");
                        request.setAttribute("download", "<a href=\"/Servlet3.0Study/download?name="+fileName+"\" rel=\"nofollow\">"+fileName+"</a>");
                        NewFile(fileName);
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message","错误信息: " + ex.getMessage());
        }
        // 跳转到 upload.jsp
        request.getServletContext().getRequestDispatcher("/upload.jsp").forward(request, response);
    }
    
	public Connection GetConnection() {//与数据库建立连接
        String url = "jdbc:mysql://localhost:3306/ListSystem";//与本机的3306端口建立连接，进入数据库listsystem
        String driverName = "com.mysql.jdbc.Driver";//驱动注册
        String userName = "root";
        String password = "123456";
        Connection conn = null;//用于建立与数据库的连接
        try{
            Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作 
            conn = DriverManager.getConnection(url, userName, password);
        }catch(Exception e){
            System.out.println(e);
        }
        return conn;
    }
	
	private int hasfile(String filename) {//判断当前上传的教材是否存在
		Connection conn = GetConnection();
		String sql = "select * from File_t";
		Statement stmt = null;
		int flag = 0,FileID = 0;
        try {
        	stmt = conn.createStatement();
        	ResultSet rs = stmt.executeQuery(sql);
        	while(rs.next()) {
        		String FileName = rs.getString("FileName");
        		FileID = rs.getInt("FileID");
        		if(filename.equals(FileName)) {
        			flag = 1;
        			break;
        		}
        	}
        	rs.close();
        	stmt.close();
        	conn.close();
        }catch(SQLException e) {
        	e.printStackTrace();
        }finally {
        	try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        if(flag == 1)
        	return -1;
		return FileID;
	}
	
	private void NewFile(String filename) {//上传新教材
		int fid = hasfile(filename)+1;
		//System.out.println("test");
		if(fid == -1) {
			System.out.println("文件已存在!");
		}
		else {
			Connection conn = GetConnection();
			String sql = "insert into File_t values(\""+fid+"\",\""+filename+"\");";
	    	Statement stmt = null;
	        try {
	            if(conn != null)
	                stmt = conn.createStatement();
	            if(stmt != null)
	                stmt.execute(sql);
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }finally {
	            try {
	                if(stmt != null)    
	                    stmt.close();
	                if(conn != null)
	                    conn.close();
	                stmt = null;
	                conn = null;
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        System.out.println("上传成功！");
		}
	}
}